package com.skd.mall.product.service.impl;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.skd.mall.product.dao.AttrAttrgroupRelationDao;
import com.skd.mall.product.entity.AttrAttrgroupRelationEntity;
import com.skd.mall.product.entity.CategoryEntity;
import com.skd.mall.product.service.AttrAttrgroupRelationService;
import com.skd.mall.product.service.AttrGroupService;
import com.skd.mall.product.service.CategoryService;
import com.skd.mall.product.vo.AttrAttrgroupRelationVo;
import com.skd.mall.product.vo.AttrResponseVo;
import com.skd.mall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skd.common.utils.PageUtils;
import com.skd.common.utils.Query;

import com.skd.mall.product.dao.AttrDao;
import com.skd.mall.product.entity.AttrEntity;
import com.skd.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Transactional
    @Override
    public void saveAttr(AttrVo vo) {
        //实现规格参数的保存
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(vo,attr);
        this.save(attr);
        //设置相关属性
        System.out.println(vo.getAttrGroupId());
        if(vo.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelation.setAttrId(attr.getAttrId());
            attrAttrgroupRelation.setAttrGroupId(vo.getAttrGroupId());
            attrAttrgroupRelationService.save(attrAttrgroupRelation);
        }
    }

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrGroupService attrGroupService;

    @Transactional
    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if(attrType.equals("sale")){
            wrapper.eq("attr_type",0).or().eq("attr_type",2);
        }
        // 1.根据类别编号查询
        if(catelogId != 0){
            wrapper.eq("catelog_id",catelogId);
        }
        // 2.根据key 模糊查询
        if (params.get("key")!=null){
            String key = (String) params.get("key");
            wrapper.and((w) ->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        //3分页查询
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils= new PageUtils(page);
        //4查询所属分类
        if(!attrType.equals("sale")){
            List<AttrEntity> records = page.getRecords();
            List<AttrResponseVo> list = records.stream().map((attrEntity) ->{
                AttrResponseVo responseVo = new AttrResponseVo();
                BeanUtils.copyProperties(attrEntity,responseVo);
                responseVo.setCatelogName(categoryService.getOne(
                        new QueryWrapper<CategoryEntity>().eq("cat_id",attrEntity.getCatelogId())).getName());//getById(attrEntity.getCatelogId())
                Long attrGroupId = attrAttrgroupRelationService.getOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()))
                        .getAttrGroupId();
                String attrGroupName = attrGroupService.getById(attrGroupId).getAttrGroupName();
                responseVo.setGroupName(attrGroupName);
                return responseVo;
            }).collect(Collectors.toList());

            pageUtils.setList(list);
        }
        return pageUtils;
    }

    @Autowired
    private AttrService attrService;
    @Transactional
    @Override
    public void updateAllById(AttrResponseVo attrResponseVo) {
        //先更新主表
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrResponseVo,attrEntity);
        attrService.updateById(attrEntity);
        //更新关系表
        AttrAttrgroupRelationEntity aagr = attrAttrgroupRelationService.getOne(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrResponseVo.getAttrId()));//attrResponseVo.getAttrId()
        aagr.setAttrGroupId(attrResponseVo.getAttrGroupId());
        attrAttrgroupRelationService.update(
                aagr,
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrResponseVo.getAttrId())
        );
    }

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Override
    public void removeByIdsDetail(Long[] attrIds) {
        //删除关联表信息
        for (Long attrId : attrIds) {
            attrAttrgroupRelationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrId));
        }
        //删除主表中信息
        this.removeByIds(Arrays.asList(attrIds));
    }

    @Autowired
    private AttrDao attrDao;
    @Override
    public PageUtils queryAddAttr(Map<String, Object> params, Integer attrGroupId) {
        try {
        List<AttrEntity> attrEntities = new ArrayList<>();

        String key = (String) params.get("key");
        //找出不属于本组的属性
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelations = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().notIn("attr_group_id", attrGroupId));
        //通过中间表找到属性主表
        attrAttrgroupRelations.stream().forEach((entity) ->{
            if (!key.isEmpty()){
                AttrEntity attr = attrDao.selectOne(
                        new QueryWrapper<AttrEntity>().eq("attr_id", entity.getAttrId())
                                .and(i -> i.eq("attr_id", key).or().like("attr_name", key))
                );
            }AttrEntity attr = attrDao.selectOne(new QueryWrapper<AttrEntity>().eq("attr_id", entity.getAttrId()));
            attrEntities.add(attr);
        });
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );
        page.setTotal(attrEntities.size());
         PageUtils pageUtils = new PageUtils(page);
         pageUtils.setList(attrEntities);
        return pageUtils;}catch (MybatisPlusException exception){
            return new PageUtils(0,0,0,0,null);
        }
    }

    @Override
    public void AddNewRelation(List<AttrAttrgroupRelationVo> attrAttrgroupRelationVos) {
        for (AttrAttrgroupRelationVo attrAttrgroupRelationVo : attrAttrgroupRelationVos) {
            attrAttrgroupRelationService.save(
                    new AttrAttrgroupRelationEntity(
                            null,attrAttrgroupRelationVo.getAttrId(),attrAttrgroupRelationVo.getAttrGroupId(),null));
        }
    }

    @Override
    public void deleteRelation(List<AttrResponseVo> attrResponseVos) {
        for (AttrResponseVo vo : attrResponseVos) {
            attrAttrgroupRelationDao.delete(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq(
                            "attr_id",vo.getAttrId()).and(i ->i.eq("attr_group_id",vo.getAttrGroupId()))
            );
        }
    }
}